package com.hmall.item.web;

import com.hmall.common.dto.PageDTO;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
@Slf4j
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     *分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO list(Integer page, Integer size){
        log.info("分页查询：page：{}，size{}",page,size);
        PageDTO<Item> pageDTO = itemService.pageList(page,size);
        return pageDTO;
    }

    /**
     * 根据id查询商品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id){
        log.info("根据id查询商品，{}",id);
        Item item = itemService.getById(id);
        return item;
    }

    @PutMapping
    public void update(@RequestBody Item item){
        itemService.updateById(item);
        item.setPrice(item.getPrice() * 100);
        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_INSERT_KEY,item);
    }



    /**
     * 新增商品
     * @param item
     */
    @PostMapping
    public void addItem(@RequestBody Item item){
        log.info("新增商品：{}",item);
        item.setPrice(item.getPrice() * 100);
        itemService.save(item);

        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_INSERT_KEY,item);
    }

    /**
     * 上架、下架商品
     * @param id
     * @param status
     */
    @PutMapping("status/{id}/{status}")
    public void changeStatus(@PathVariable Long id,@PathVariable Integer status){
        log.info("修改商品状态，商品id：{}，修改状态为：{}",id,status);
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);

        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_INSERT_KEY,item);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        log.info("根据id删除商品：{}",id);
        itemService.delete(id);
        rabbitTemplate.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.HMALL_DELETE_KEY,id);
    }

    @GetMapping
    public List<Item> list(){
        List<Item> list = itemService.list();
        return list;
    }



}
